﻿using System;
using System.Collections.Generic;
using Swift;

namespace Server
{
    /// <summary>
    /// 玩家实时匹配对手
    /// </summary>
    public class MatchBoard : Component, IFrameDrived
    {
        UserPort UP;

        // 战斗房间管理
        BattleRoomManager BtrMgr;

        // 等待匹配的玩家
        List<string> waiting4Player = new List<string>();

        // 等待匹配电脑的玩家
        StableDictionary<string, string> waiting4Robot = new StableDictionary<string, string>();

        public override void Init()
        {
            BtrMgr = GetCom<BattleRoomManager>();
            UP = GetCom<UserPort>();
            GetCom<LoginManager>().OnUserDisconnecting += OnUserDisconnected;

            UP.OnMessage("MatchIn", OnIn);
            UP.OnRequest("CancelMatchIn", OnCancel);
            UP.OnMessage("MatchRobot", OnMatchRobot);
        }

        // 加入匹配等待列表
        void OnIn(Session s, IReadableBuffer data)
        {
            bool ranking = data.ReadBool();
            if (!waiting4Player.Contains(s.ID))
                waiting4Player.Add(s.ID);
        }

        // 玩家退出或掉线
        void OnUserDisconnected(Session s)
        {
            RemoveWaitings(s.ID);
        }

        // 从匹配列表移除
        void OnCancel(Session s, IReadableBuffer data, IWriteableBuffer buff)
        {
            waiting4Player.Remove(s.ID);
            buff.Write(true);
        }

        // 匹配机器人
        void OnMatchRobot(Session s, IReadableBuffer data)
        {
            var aiType = data.ReadString();
            if (waiting4Robot.ContainsKey(s.ID))
                waiting4Robot.Remove(s.ID);

            waiting4Robot[s.ID] = aiType;
        }

        // 用户退出匹配等待
        public void RemoveWaitings(string usr)
        {
            if (waiting4Player.Contains(usr))
                waiting4Player.Remove(usr);
        }

        // 不断尝试匹配用户，匹配到了就开战
        public void OnTimeElapsed(int te)
        {
            // 玩家两两匹配
            while (waiting4Player.Count >= 2)
            {
                var usr1 = waiting4Player[0];
                var usr2 = waiting4Player[1];
                waiting4Player.RemoveRange(0, 2);

                var r = BtrMgr.CreatePVPRoom(usr1, usr2);
                if (r == null)
                    return;

                r.WinnerAward = 5;
                r.LoserAward = 0;
                r.BattleBegin(RandomUtils.RandomNext());
            }

            // 匹配电脑 AI
            foreach (var usr in waiting4Robot.Keys)
            {
                var lvID = waiting4Robot[usr];
                var r = BtrMgr.CreatePVERoom(usr, lvID);
                r.BattleBegin(RandomUtils.RandomNext());
            }
            waiting4Robot.Clear();
        }
    }
}
